/**
 * @retrun {init} 返回随机数
 * @param {int} start 开始值
 * @param {init} end 结束值
 */

const getRandomNumber = function (start, end) {
    return Math.floor(Math.random() * (end - start + 1)) + start;
}

/**
 * 
 * @param {Function} fn 执行函数
 * @param {Number} timeGap 时间间隔
 */
const debounce = function (fn, timeGap = 1000) {
    let timer = null;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn();
        }, timeGap)
    }
}

/**
 * 
 * @param {Function} fn 执行函数
 * @param {Number} timeGap 时间间隔
 */

const throttle = function (fn, timeGap = 1000) {
    let canRun = true;
    return function () {
        if (!canRun) {
            return;
        }
        setTimeout(() => {
            fn();
            canRun = true;
        }, timeGap);
        canRun = false;
    }
}
/**
 * 
 * @param {Object} obj 需要取值的对象
 * @param {*} pathArr 取值的路径，比如 要取 obj.a.b.c , 就 'a.b.c';
 * @param {*} defaultVal 如果在取值过程中取值失败，返回的默认值
 * 
 * 说明：如果要去 obj.a.b.c 的值，getDeepValue(obj,'a.b.c','defaultValue') 
 */

const getDeepValue = function (obj = {}, pathArr = "", defaultVal = false) {

    if (typeof pathArr != "string") {
        console.warn('expect String ,but get', typeof pathArr, 'so return default empty string ');
        return "";
    }
    let path = pathArr.split('.');
    if (!path.length) {
        return '';
    }
    return path.reduce((prev, cur) => (prev && prev[cur] !== undefined) ? prev[cur] : defaultVal, obj);
}


const getRandomColor = function(){
    let colorStr = "0123456789abcdef";

    let randColor = "#";
    for (let i = 0; i < 6; i++) {
        randColor += colorStr.charAt(getRandomNumber(0, 15));
    }
    return randColor;
}

export {
    getRandomNumber,
    getRandomColor,
    debounce,
    throttle,
    getDeepValue
}